import cache from '../../api/cache'
import {
  request
} from "../../requests/post.js";

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    arraySex: ['女', '男'],
    user:{
      userName: null,
      sex: 1,
      age: null,
      telephone: null,
      upAge: null,
      downAge: null,
    },
    listShowFlag: false,
    userInfo: null
  },

  // 设置性别
  sexPickerChange(e) {
    this.setData({"user.sex": e.detail.value})
  },

  bindNameChange(e) {
    this.setData({
      "user.userName": e.detail.value
    })
  },


  bindAgeChange(e) {
    let age = e.detail.value;
    if (age) {
      age = parseInt(age);
      if (age < 0 || age > 130 || isNaN(age)) {
        wx.showToast({
          title: '年龄必须在0到130岁之间',
          icon: 'none'
        });
      } else {
        // 年龄合法，可以继续后续操作
        console.log('年龄合法：', age);
      }
    }

    this.setData({
      "user.age": e.detail.value
    })
  },

  bindUpAgeChange(e) {
    let age = e.detail.value;
    if (age) {
      age = parseInt(age);
      if (age < 0 || age > 130 || isNaN(age)) {
        wx.showToast({
          title: '年龄必须在0到130岁之间',
          icon: 'none'
        });
      } else {
        // 年龄合法，可以继续后续操作
        console.log('年龄合法：', age);
      }
    }

    this.setData({
      "user.upAge": e.detail.value
    })
  },

  bindDownAgeChange(e) {
    let age = e.detail.value;
    if (age) {
      age = parseInt(age);
      if (age < 0 || age > 130 || isNaN(age)) {
        wx.showToast({
          title: '年龄必须在0到130岁之间',
          icon: 'none'
        });
      } else {
        // 年龄合法，可以继续后续操作
        console.log('年龄合法：', age);
      }
    }

    this.setData({
      "user.downAge": e.detail.value
    })
  },

  validTel(tel) {
    
  },

  bindTelChange(e) {

    let tel =  e.detail.value;
    console.info("tel - " + tel)

    var mobile = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;

    if(!mobile.test(tel)){
      wx.showToast({
        title: "请输入正确的手机号",
        icon: 'none',
        duration: 3000,
      })
      // this.setData({
      //   "user.telephone": ""  
      // })
    } else {
      this.setData({
        "user.telephone": tel
      })
    }

  },

  bindDateChange(e) {
    console.log("bindDateChange - " + e.detail.value)
    this.setData({
      "user.nickName": e.detail.value
    })
  },

  submit(){
    let that = this

    if (typeof this.data.user.userName === "undefined" || this.data.user.userName === null  
      || this.data.user.userName === ''
        ) {
      wx.showToast({
        title: "请输入姓名",
        icon: 'none'
      })
    } else if (typeof this.data.user.age === "undefined" || this.data.user.age === null 
        || this.data.user.age === '') {
      wx.showToast({
        title: "请输入年龄",
        icon: 'none'
      })
    } else if (typeof this.data.user.sex === "undefined" || this.data.user.sex === null ) {
      wx.showToast({
        title: "请输入姓别",
        icon: 'none'
      })
    } else if (typeof this.data.user.telephone === "undefined" || this.data.user.telephone === null ) {
      wx.showToast({
        title: "请输入手机号",
        icon: 'none'
      })
    } else {

      request({
        url: '/xq/save_info',
        userName: that.data.user.userName,
        age: that.data.user.age,
        sex: that.data.user.sex,
        telephone: that.data.user.telephone,
        upAge: that.data.user.upAge,
        downAge: that.data.user.downAge,
        key: app.globalData.key
      }).then(result => {
        console.info(JSON.stringify(result))
        if (result.data.errorCode === 200) {
          wx.showToast({
            title: "保存成功",
            icon: 'none',
            duration: 2000,
          })
        } else {
          wx.showToast({
            title: result.data.msg,
            icon: 'none',
            duration: 2000,
          })
        }
      }, err => {
        wx.showToast({
          title: err,
          icon: 'none',
          duration: 2000,
        })
      })
    }
  },

  wxLogin() {
    // let nickName = this.data.nickName
    var timestamp = Date.now();
    timestamp = Math.floor(timestamp / 1000).toString();
    var nickName = "番薯用户" + timestamp
    console.log("nickname - " + nickName)
    if (nickName !== "" && nickName !== null) {
      console.log("nickname - 11")
      var that = this
      wx.login({
        success(res) {
          if (res.code) {
            request({
              url: '/xq/login',
              code: res.code,
              nickName: nickName
            }).then(result => {
              if (result.data.errorCode == 200) {
                cache.setOp(app.globalData.userCacheKey, result.data.data)
                // cache.setOp(app.globalData.tokenKey, result.data.data["token"])
                // app.globalData.token = result.data.data["token"]
                app.globalData.key = result.data.data["key"]
                that.setData({
                  user: result.data.data,
                  hasUserInfo: true
                })
                // 跳转到指标页
                wx.hideLoading()
                that.setData({
                  'listShowFlag': true
                })
              } else {
                wx.hideLoading()
                that.setData({
                  "iosDialog2": true
                })
                console.log('服务器异常')
              }
            }, err => {
              //调用服务端登录接口失败
              wx.hideLoading()
              that.setData({
                "iosDialog2": true
              })
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none',
        duration: 2000,
      })
    }
    
    console.log('test')
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onUnload: function () {},

  onLoad: function (options) {
    
    var user = cache.getOp(app.globalData.userCacheKey)
    
    if (user === null) {
      this.setData({
        'listShowFlag': false
      })
    } else {
      
      this.setData({
        "nickName": user.nickName
      })
      
      console.log("user.key " + user.key)
      if (typeof user.key === "undefined" || user.key === null || user.key === null) {
        this.setData({
          'listShowFlag': false
        })
        return
      }

      app.globalData.key = user.key
      
      this.setData({
        'userInfo': user,
        'listShowFlag': true,
      })

      //获取基础数据
      let that = this
      request({
        url: '/xq/get_user',
        key: user.key
      }).then(result => {
        if (result.data.errorCode === 200) {
          that.setData({
            "user": result.data.data
          })
        } else {
          wx.showToast({
            title: result.data.msg,
            icon: 'none',
            duration: 2000,
          })
        }
      })
    }
  },

})